<?php

namespace app\index\controller;

use app\common\api\controller\Error;
use app\common\api\controller\Relation;
use app\common\controller\Wechat;
use app\common\model\Activities;
use app\common\model\ActivityMembers;
use app\common\model\Levels;
use app\common\model\Member;
use app\common\model\MemberFinance;
use app\common\model\MemberPackages;
use app\common\model\MemberViews;
use app\common\model\Packages;
use app\common\model\UcenterMember;
use app\common\model\UserPerformance;
use app\common\model\UserRelation;
use think\Db;
use app\common\api\controller\User as UserApi;
use app\common\api\controller\Bonus;
use think\Request;
use think\Validate;
use think\log;

class User extends Home
{
    protected $beforeActionList = [
        'check_load' => ['except' => 'resetpwd1,mregist,regist1,regist,register,registuser,getcode,checkusernum,getopenid,recom'],
    ];

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取用户信息
     * @return void
     */
    public function index()
    {
        $this->apiSuccess('用户信息', $this->userInfo);
    }

    /**
     * 是否应该获取奖励
     */
    public function isBonus()
    {
        $activityInfo = Activities::where('start_time', '<=', time())
            ->where('end_time', '>', time())
            ->where('status', 1)
            ->find();
        $number = 0;
        if ($activityInfo) {
            $number = $activityInfo->total_num - $activityInfo->has_num;
        }

        $aid = Db('transport')->where('uid', $this->uid)->where('status', 1)->find();
        if ($aid) {
            $number = 0;
        }

        $number = max($number, 0);
        $this->apiSuccess('', $number);
    }

    /**
     * 资产统计
     */
    public function finance()
    {
        $bonus = Db('bonus_total')->where('userid', $this->uid)->find();
        $bonus1 = !empty($bonus) ? $bonus['bonus1'] : 0.00;
        $bonus2 = !empty($bonus) ? $bonus['bonus2'] : 0.00;

        $data = [
            'hasbill' => $this->userInfo['hasbill'],
            'hasmoney' => $this->userInfo['hasmoney'],
            'hascp' => $this->userInfo['hascp'],
            'bonus1' => $bonus1,
            'bonus2' => $bonus2,
        ];

        $this->apiSuccess('资产统计', $data);
    }

    /**
     * 获取流量包
     */
    public function getPackages()
    {
        $uid = $this->uid;
        $type = input('type', 1);
        switch ($type) {
            case 1:
                $packages = Packages::order('id asc')->select();
                foreach ($packages as $v1) {
                    $num = MemberPackages::where('uid', $uid)->where('package_id', $v1->id)->where('status', 1)->count();
                    $v1->num = $num;
                }
                break;
            case 2:
                $packages = MemberPackages::where('uid', $uid)->where('status', 1)->select();
                if ($packages) {
                    foreach ($packages as $v2) {
                        $packageInfo = Packages::where('id', $v2->package_id)->find();
                        $v2->name = $packageInfo->name;
                        $v2->cost = $packageInfo->cost;
                        $v2->product = $packageInfo->product;
                    }
                }
                break;
            case 3:
                $packages = MemberPackages::where('uid', $uid)->where('status', 0)->select();
                if ($packages) {
                    foreach ($packages as $v3) {
                        $packageInfo = Packages::where('id', $v3->package_id)->find();
                        $v3->name = $packageInfo->name;
                        $v3->cost = $packageInfo->cost;
                        $v3->product = $packageInfo->product;
                    }
                }
                break;
        }

        $this->apiSuccess('流量包', $packages);
    }

    /**
     * 购买消费包
     */
    public function buyPackage()
    {
        $uid = $this->uid;
        $id = input('id');
        $packageInfo = Packages::where('status', 1)->find($id);
        if (!$packageInfo) {
            $this->apiError('该流量包不存在！');
        }
        $memberModel = Member::find($uid);
        if ($memberModel->start_sign_time <= 0) {
            $this->apiError('尚未签到，不可购买消费包！');
        }
        $num = MemberPackages::where('uid', $uid)->where('package_id', $id)->where('status', 1)->count();
        if ($packageInfo->number <= $num) {
            $this->apiError('暂时不可购买该流量包');
        }
        $password = input('password');
        if ($memberModel->psd2 != $password) {
            $this->apiError('支付密码错误！');
        }

        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();

        $moneytype = input('type', 2);
        switch ($moneytype) {
            case 1:
                $field = 'hasactive';
                break;
            case 2:
                $field = 'hastdb';
                break;
            default:
                $this->apiError('非法操作！');
                break;
        }

        if ($memberFinanceModel->$field < $packageInfo->cost) {
            $this->apiError('余额不足！');
        }

        $max_rank = MemberPackages::where('uid', $uid)->where('package_id', $id)->order('id desc')->value('rank');
        $rank = $max_rank + 1;
        $total_days = $packageInfo->min_days + $rank - 1;
        $total_days = min($total_days, $packageInfo->max_days);

        $per_output = round($packageInfo->product / $total_days, 4);

        $memberPackageModel = new MemberPackages();
        $memberPackageModel->uid = $uid;
        $memberPackageModel->package_id = $id;
        $memberPackageModel->total_days = $total_days;
        $memberPackageModel->rank = $rank;
        $memberPackageModel->per_output = $per_output;

        Db::startTrans();
        try {
            $memberPackageModel->save();

            // 产生成长值
            $memberFinanceModel->$field -= $packageInfo->cost;
            $growthRate = get_bonus_rule('growth_rate');
            $growthMoney = $packageInfo->cost * $growthRate;
            $memberFinanceModel->hasgrowth += $growthMoney;
            $memberFinanceModel->allgrowth += $growthMoney;

            $memberFinanceModel->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->apiError('兑换失败');
        }

        $memberFinanceModel = MemberFinance::where('uid', $uid)->find();
        $type = array('recordtype' => 0, 'changetype' => 20, 'moneytype' => $moneytype);
        $money = array('money' => $packageInfo->cost, 'hasmoney' => $memberFinanceModel->$field);
        money_change($type, $uid, 0, $money);
        unset($type, $money);

        $type = array('recordtype' => 1, 'changetype' => 20, 'moneytype' => 7);
        $money = array('money' => $growthMoney, 'hasmoney' => $memberFinanceModel->hasgrowth);
        money_change($type, $uid, 0, $money);
        unset($type, $money);

        if ($memberModel->is_pay == 0) {
            $memberModel->is_pay = 1;
        }
        $bonus = new Bonus();
        if ($memberModel->package_id < $id) {
            $memberModel->package_id = $id;
            $bonus->updateRank1($uid);//包级别更新影响成长值
        }
        $memberModel->save();

        $bonus->bonusRecom($uid, $packageInfo->cost);//推荐奖增加贡献值
        $bonus->addAchievement($uid, $packageInfo->cost, true);//团队增加成长值
        $bonus->updateRank($uid);// 团队升级

        $id = Activities::isExistActivity();
        if ($id > 0) {
            $isExist = ActivityMembers::where('activity_id', $id)->where('uid', $uid)->value('id');
            if (!$isExist) {
                $ret = ActivityMembers::create([
                    'uid' => $uid,
                    'activity_id' => $id,
                ]);
                if ($ret->id > 0) {
                    Activities::incNum($id);
                }
            }
        }

        $this->apiSuccess('兑换成功');

    }

    /**
     * 得到openid
     */
    public function getOpenId()
    {
        $uid = is_login();
        $user = Db('member')->where('uid', $uid)->find();
        if ($user['open_id'] && $user['icon'] && $user['nickname'] && $user['is_attention']) {
            return;
        }
        $wechat = new Wechat();
        $code = input('code');
        if (!$code) {
            $purl = 'http://' . $_SERVER['HTTP_HOST'] . '/index/User/getOpenId';
            $url = $wechat->get_authorize_url($purl);
            header("Location:" . $url);
            exit;
        }
        $data1 = $wechat->get_access_token($code);
        $openId = $data1['openid'];
        $data2 = $wechat->get_token();
        $accessToken = $data2['access_token'];

        $info = $wechat->get_user_info($accessToken, $openId);
        if ($info['subscribe'] == 0) {
            $this->error('请先关注公众号！', url('attention'));
        }
        $data = [
            'icon' => $info['headimgurl'],
            'open_id' => $openId,
            'nickname' => $info['nickname'],
            'is_attention' => $info['subscribe']
        ];

        Db('member')->where('uid', $uid)->update($data);
        $this->redirect('User/index');
    }

    /**
     * 关注公众号
     * @return mixed
     */
    public function attention()
    {
        if (!is_weixin()) {
            $this->error('请使用微信扫一扫！');
        }
        $this->assign('title', "关注公众号");
        return $this->fetch('');
    }

    /**
     * 推荐会员
     * @return mixed
     */
    public function userIndex()
    {
        $uid = $this->uid;
        $page = input('page');
        $start = ($page - 1) * self::$totalList;

        $map = [
            'tuijianid' => $uid,
            'status' => ['>=', 1]
        ];

        $lists = Member::where($map)
            ->order('active_time desc')
            ->limit($start, self::$totalList)
            ->select();

        $totalCount = Member::where($map)
            ->count();

        if ($totalCount > 0) {
            $today = strtotime('today');
            foreach ($lists as $v) {
                $v->userrank_name = Levels::where('id', $v->userrank)->value('name');
                $v->isSign = Db('member_signin')->where('uid', $v->uid)->where('create_time', $today)->value('id') ? '完成' : '未完成';
                $v->hasgrowth = MemberFinance::where('uid', $v->uid)->value('hasgrowth');
            }
        }

        $this->apiSuccess('推荐会员列表', ['list' => $lists, 'totalCount' => $totalCount]);
    }

    /**
     * 个人信息认证
     * @return mixed
     */
    public function authApply()
    {
        $uid = $this->uid;
        $memberObj = Member::find($uid);
        if ($memberObj->status != 1) {
            $this->apiError('当前不可申请！');
        }

        $data = input('post.');
        if (!$data['realname'] || !$data['IDcard'] || !$data['ID1'] || !$data['ID2']) {
            $this->apiError('真实姓名，身份证号码，身份证正面照，反面照缺一不可！');
        }

        $memberObj->realname = $data['realname'];
        $memberObj->IDcard = $data['IDcard'];
        $memberObj->ID1 = $data['ID1'];
        $memberObj->ID2 = $data['ID2'];
        $memberObj->status = 2;

        $res = $memberObj->save();
        if ($res) {

            $ucenterModel = UcenterMember::find($uid);
            $ucenterModel->status = 2;
            $ucenterModel->save();

            $is_auto_auth = config('IS_AUTO_AUTH');
            $isOpenPay = config('IS_OPEN_PAY');
            if ($is_auto_auth == 1) {
                $memberModel = Member::find($uid);
                Db::startTrans();
                try {
                    $packageInfo = Packages::order('id asc')->find();

                    $memberModel->package_id = $packageInfo->id;
                    $memberModel->status = 3;
                    $memberModel->save();

                    $ucenterModel->status = 3;
                    $ucenterModel->save();

                    $per_output = round($packageInfo->product / $packageInfo->min_days, 4);

                    $memberPackagesModel = new MemberPackages();
                    $memberPackagesModel->uid = $uid;
                    $memberPackagesModel->package_id = $packageInfo->id;
                    $memberPackagesModel->total_days = $packageInfo->min_days;
                    $memberPackagesModel->rank = 1;
                    $memberPackagesModel->per_output = $per_output;

                    $memberPackagesModel->save();
                    Db::commit();

                    $bonus = new Bonus();
//                $bonus->bonusRecom($uid, $packageInfo->cost);//推荐奖
                    $bonus->addAchievement($uid, $packageInfo->cost);//团队增加成长值
                    $bonus->updateRank($uid);// 团队升级

                } catch (\Exception $e) {
                    Db::rollback();
//                    $this->error($e->getMessage());
                }

                $isOpenPay = "0";
            }

            $this->apiSuccess('申请提交成功！', ['is_open_pay' => $isOpenPay]);
        } else {
            $this->apiError('申请提交失败！');
        }
    }

    /**
     * 个人信息认证缴费
     */
    public function userAuthPay()
    {
        $uid = $this->uid;
        $memberObj = Member::find($uid);
        if ($memberObj->status != 2) {
            $this->apiError('当前不可缴费！');
        }

        $data = input('post.');
        if (!$data['icon']) {
            $this->apiError('必须上传打款截图！');
        }

        $memberObj->auth_icon = $data['icon'];
        $res = $memberObj->save();
        if ($res) {
            $this->apiSuccess('请耐心等待！');
        } else {
            $this->apiError('申请提交失败！');
        }
    }

    /**
     * 重置
     */
    public function resetPwd1()
    {
        $mobile = input('mobile');
        $code = input('code');
        $password = input('password');
        if (!$mobile || !$password || !$code) {
            $this->apiError('参数缺失！');
        }

        $res = $this->checkCode($mobile, $code);
        if ($res['status'] == 0) {
            $this->apiError($res['msg']);
        }

        $user = Db('member')->where('mobile', $mobile)->where('status', 1)->find();
        if (!$user) {
            $this->apiError('该用户不存在！');
        }
        $uid = $user['uid'];
        $upassword = think_ucenter_md5($password, PASSWORD_KEY);
        Db::startTrans();
        try {
            Db('member')->where('uid', $uid)->setField('psd1', $password);
            Db('ucenter_member')->where('id', $uid)->setField('password', $upassword);
            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->apiError('密码重置失败');
        }

        $this->destroyCode($user['mobile']);
        $this->apiSuccess('密码重置成功');
    }

    /**
     * 设置或更新登录密码
     */
    public function changePwd1()
    {
        $uid = $this->uid;
        $opassword = input('opassword');
        $password = input('password');
        if (!$opassword || !$password) {
            $this->apiError('参数缺失！');
        }

        $user = Db('member')->where('uid', $uid)->field('mobile,psd1')->find();
        if ($user['psd1'] != $opassword) {
            $this->apiError('旧密码输入错误！');
        }

        if ($user['psd1'] == $password) {
            $this->apiError('新密码输入错误！');
        }
//        $res = $this->checkCode($user['mobile'], $code);
//        if ($res['status'] == 0) {
//            $this->apiError($res['msg']);
//        }

        $upassword = think_ucenter_md5($password, PASSWORD_KEY);
        Db::startTrans();
        try {
            Db('member')->where('uid', $uid)->setField('psd1', $password);
            Db('ucenter_member')->where('id', $uid)->setField('password', $upassword);
            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->apiError('密码修改失败');
        }

//        $this->destroyCode($user['mobile']);
        $this->apiSuccess('密码修改成功');
    }

    /**
     * 设置或更新资产密码
     */
    public function changePwd2()
    {
        $uid = $this->uid;
        $opassword = input('opassword');
        $password = input('password');
        if (!$opassword || !$password) {
            $this->apiError('参数缺失！');
        }

        $user = Db('member')->where('uid', $uid)->field('mobile,psd2')->find();
        if ($user['psd2'] != $opassword) {
            $this->apiError('旧密码输入错误！');
        }

        if ($user['psd2'] == $password) {
            $this->apiError('新密码输入错误！');
        }
//        $res = $this->checkCode($user['mobile'], $code);
//        if ($res['status'] == 0) {
//            $this->apiError($res['msg']);
//        }

        $upassword = think_ucenter_md5($password, PASSWORD_KEY);
        Db::startTrans();
        try {
            Db('member')->where('uid', $uid)->setField('psd2', $password);
            Db('ucenter_member')->where('id', $uid)->setField('password2', $upassword);
            // 提交事务
            Db::commit();

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->apiError('密码修改失败');
        }

//        $this->destroyCode($user['mobile']);
        $this->apiSuccess('密码修改成功');
    }

    /**
     * 更新头像
     * @return array
     */
    public function changeHeadimg()
    {
        $uid = $this->uid;
        $headimg = input('headimg');
        if (!$headimg) {
            $this->apiError('参数缺失');
        }
        $res = Db('member')->where('uid', $uid)->update(['icon' => $headimg]);
        if ($res) {
            $this->apiSuccess('更新成功');
        } else {
            $this->apiError('更新失败');
        }
    }

    /**
     * 更新支付宝收款码
     * @return array
     */
    public function changeAlipay()
    {
        $uid = $this->uid;
        $path = input('path');
        if (!$path) {
            $this->apiError('参数缺失');
        }
        $res = Db('member')->where('uid', $uid)->update(['alipay' => $path]);
        if ($res) {
            $this->apiSuccess('更新成功');
        } else {
            $this->apiError('更新失败');
        }
    }

    /**
     * 更新微信收款码
     * @return array
     */
    public function changeWechat()
    {
        $uid = $this->uid;
        $path = input('path');
        if (!$path) {
            $this->apiError('参数缺失');
        }
        $res = Db('member')->where('uid', $uid)->update(['wechat' => $path]);
        if ($res) {
            $this->apiSuccess('更新成功');
        } else {
            $this->apiError('更新失败');
        }
    }

    /**
     * 用户账户
     * @return mixed
     */
    public function updateMemberMsg()
    {
        $uid = $this->uid;
        $memberModel = Member::find($uid);
        $data = input('post.');

        switch ($data['type']) {
            case 1:
                if (!$data['bank_name'] || !$data['bank_number'] || !$data['bank_address']) {
                    $this->apiError('银行名称，银行卡号，开户行都不能为空！');
                }
                $memberModel->realname = $data['realname'];
                $memberModel->bank_name = $data['bank_name'];
                $memberModel->bank_number = $data['bank_number'];
                $memberModel->bank_address = $data['bank_address'];
                break;
            case 2:
                if (!$data['alipay']) {
                    $this->apiError('支付宝账号不能为空！');
                }
                $memberModel->realname = $data['realname'];
                $memberModel->alipay = $data['alipay'];
                break;
            case 3:
                if (!$data['wechat']) {
                    $this->apiError('微信账号不能为空！');
                }
                $memberModel->realname = $data['realname'];
                $memberModel->wechat = $data['wechat'];
                break;
        }
        $res = $memberModel->save();
        if ($res) {
            $this->apiSuccess('更新成功');
        } else {
            $this->apiError('更新失败');
        }
    }

    /**
     * 活跃值兑换通兑宝的比例
     */
    public function getRate()
    {
        $uid = $this->uid;
        $userrank = Member::where('uid', $uid)->value('userrank');
        $active_tdb_rate = Levels::where('id', $userrank)->value('active_tdb_rate');

        $this->apiSuccess('活跃值兑换通兑宝的比例', $active_tdb_rate * 100);
    }

    /**
     * 签到页面初始化
     */
    public function signInit()
    {
        $uid = $this->uid;
        $signDays = Member::where('uid', $uid)->value('sign_days');

        $list = [];
        $end = strtotime('today');

        $todayInfo = [];
        for ($i = 0; $i < 7; $i++) {
            $time = $end - $i * 86400;
            $date = date('m/d', $time);
            if ($i == 0) {
                $date = '今天';
            }

            $id = Db('member_signin')->where('uid', $uid)->where('create_time', $time)->value('id');
            $flag = $id ? true : false;

            $item = [
                'date' => $date,
                'flag' => $flag
            ];

            if ($i == 0) {
                $todayInfo = $item;
            } else {
                array_push($list, $item);
            }
        }

        $list = array_reverse($list);
        array_unshift($list, $todayInfo);

        $isSigned = false;
        $today = strtotime('today');
        $id = Db('member_signin')->where('uid', $uid)->where('create_time', $today)->value('id');
        if ($id) {
            $isSigned = true;
        }

        $num = MemberViews::where('uid', $uid)->where('date_time', $today)->value('num');
        $this->apiSuccess('签到页面初始化', ['sign_days' => $signDays, 'list' => $list, 'is_signed' => $isSigned, 'num' => $num]);
    }

    /**
     * 完成签到（弃用）
     */
    public function finishSign()
    {
        $uid = $this->uid;
        $today = strtotime('today');
        $id = Db('member_signin')->where('uid', $uid)->where('create_time', $today)->value('id');
        if ($id) {
            $this->apiError('今日已签到');
        }

        $data = [
            'uid' => $uid,
            'create_time' => $today,
            'status' => 1,
        ];

        $res = Db('member_signin')->insert($data);
        if ($res) {

            Member::where('uid', $uid)->setInc('sign_days');

            $this->apiSuccess('完成签到');
        } else {
            $this->apiError('签到失败');
        }
    }

    /**
     * 观看视频签到
     */
    public function finishView()
    {
        $uid = $this->uid;
        $today = strtotime('today');

        $viewInfo = MemberViews::where('uid', $uid)->where('date_time', $today)->find();
        if (!$viewInfo) {
            $vdata = [
                'uid' => $uid
            ];

            $res = MemberViews::create($vdata);
            if ($res->id > 0) {
                $this->apiSuccess('记录成功');
            } else {
                $this->apiError('记录失败');
            }
        }

        $msg = '记录';
        Db::startTrans();
        try {
            $viewInfo->num += 1;
            $viewInfo->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->apiError('记录失败');
        }

        // 今日签到
        if ($viewInfo->num >= 6) {
            $memberModel = Member::find($uid);
            $packageInfo = Packages::where('status', 1)->order('id asc')->find();
            $bonus = new Bonus();
            $data = [
                'uid' => $uid,
                'create_time' => $today,
                'status' => 1,
            ];

            Db('member_signin')->insert($data);
            if ($memberModel->start_sign_time <= 0) {
                $memberModel->start_sign_time = time();
                Db('member')->where('uid', $memberModel->tuijianid)->setInc('recom_num', 1);
                $bonus->updateRank1($memberModel->tuijianid);//推荐人数影响级别

                $bonus->bonusRecom($uid, $packageInfo->cost);//推荐奖增加贡献值
            }
            $memberModel->end_sign_time = time();
            $memberModel->sign_days += 1;
            $memberModel->save();

            // 签到释放奖励（贡献值释放，消费券释放，消费包释放）
            $bonus->contribution_release($uid);
            $bonus->cp_release($uid);
            $bonus->package_release($uid);

            $msg = '签到';
        }

        $this->apiSuccess($msg . '成功');
    }

    /**
     * 升级申请
     */
    public function updateReply()
    {
        $uid = $this->uid;
        $rank = Member::where('uid', $uid)->value('update_rank');
        $updateInfo = Db('member_update')->where('uid', $uid)->where('rank', $rank)->find();
        if ($updateInfo) {
            $this->apiError('该升级已申请过');
        }

        $data = [
            'uid' => $uid,
            'rank' => $rank,
            'create_time' => time(),
            'update_time' => time(),
            'status' => 0,
        ];

        $res = Db('member_update')->insert($data);
        if ($res) {
            $this->apiSuccess('申请成功，等待审核');
        } else {
            $this->apiError('申请失败');
        }
    }
}